package com.game.service.game.turntable.config;

import com.game.service.app.Utils;
import com.game.service.db.UserScoreDaoImpl;
import com.game.service.define.RoomConfig;
import com.game.service.game.turntable.PrizeItem;
import com.game.service.game.turntable.TurntableAddConfig;
import com.game.service.windows.LogWindows;
import com.google.gson.Gson;

import java.util.ArrayList;

import static com.game.service.define.RoomConfig.GAME_ID;


public class Prize {
    private int _uid;
    private int[] _betArray;
    private PrizeList mPrizeList;//长期有效奖励
    private PrizeDailyTask mPrizeDailyTask;//每日任务

    private void init() {
        if (mPrizeList == null) {
            mPrizeList = new PrizeList(_betArray, _uid);
            System.out.println("初始化" + mPrizeList);
        }
        if (mPrizeDailyTask == null) {
            mPrizeDailyTask = new PrizeDailyTask();
            mPrizeDailyTask.initPrizeDaily(_betArray);
            String json = new Gson().toJson(mPrizeDailyTask);
            String code = String.format("UID=%s@JSON=%s@KEY=%s", _uid, json, RoomConfig.LUCKY_KEY);
            String sign = Utils.encryptMD5(code);//初始化玩家的幸运值签名
            mPrizeDailyTask.setSign(sign);//设置签名
            LogWindows.getLogWindows().printToTextArea("Init:" + code, Prize.class);

            System.out.println("初始化" + mPrizeDailyTask);
        }
    }


    public void loadDb(int gameid, int uid, int[] betArray) {
        this._uid = uid;
        this._betArray = betArray;
        PrizeDb mPrizeDb = UserScoreDaoImpl.getInstance().getPrizeList(gameid, uid);
        if (mPrizeDb != null && mPrizeDb.getPrize_json() != null && mPrizeDb.getPrize_json().length() > 2) {
            mPrizeList = new Gson().fromJson(mPrizeDb.getPrize_json(), PrizeList.class);
            mPrizeDailyTask = new Gson().fromJson(mPrizeDb.getPrize_daily_json(), PrizeDailyTask.class);
           // resetPrizeDailyError(mPrizeDb.getPrize_daily_json());//写入前,先判断数据是否正常,异常则重置,并且写入日志
            resetPrizeDaily();//写入前,先判断是否需要重置每日活动
        } else {
            //插入新的数据
            init();
            PrizeDb mPrizeDbInit = new PrizeDb();
            mPrizeDbInit.setGameid(gameid);
            mPrizeDbInit.setUid(uid);
            String prizeJson = new Gson().toJson(mPrizeList);
            mPrizeDbInit.setPrize_json(prizeJson);
            String prizeDailyJson = new Gson().toJson(mPrizeDailyTask);
            mPrizeDbInit.setPrize_daily_json(prizeDailyJson);

            UserScoreDaoImpl.getInstance().addUserPrize(mPrizeDbInit);
        }
    }

    private boolean checkingDailyTask(String jsonInit, String sign) {
        PrizeDailyTask checkingJson = new Gson().fromJson(jsonInit, PrizeDailyTask.class);
        checkingJson.setSign("");
        String json = new Gson().toJson(checkingJson);
        return Utils.checkingDailyTask(_uid, json, sign);
    }

    public void add(int betIndex, PrizeItem item) {
        mPrizeList.getPrizeArray().get(betIndex)[item.getId()] += 1;
        mPrizeDailyTask.getPrizeArray().get(betIndex)[item.getId()] += 1;//统计每日的游戏中奖信息
//        int counts = mPrizeList.getPrizeArrayLuckyCard().get(betIndex)[item.getId()];
//        if (counts == 0) {
//            mPrizeList.getPrizeArrayLuckyCard().get(betIndex)[item.getId()] += 1;
//        }
        mPrizeList.getPrizeArrayLuckyValue()[betIndex] += 1;//统计各类押注总次数
        int prizeLuckyValue = _betArray[betIndex] / 10;//每10钻赠送一个幸运积分
        mPrizeList.setPrizeLuckyValueAdd(prizeLuckyValue);//增加积分

        mPrizeDailyTask.getPrizeDailyList().get(betIndex).setPlayCountsAdd();
        new Thread(this::write).start();

    }

    /***
     *写回数据库
     */
    public void write() {
        resetPrizeDaily();//写入前,先判断是否需要重置每日活动
        PrizeDb mPrizeDbInit = new PrizeDb();
        mPrizeDbInit.setGameid(GAME_ID);
        mPrizeDbInit.setUid(_uid);
        String prizeJson = new Gson().toJson(mPrizeList);
        mPrizeDbInit.setPrize_json(prizeJson);
        //加密数据
        String json = new Gson().toJson(mPrizeDailyTask);
        String code = String.format("UID=%s@JSON=%s@KEY=%s", _uid, json, RoomConfig.LUCKY_KEY);
        String sign = Utils.encryptMD5(code);
        mPrizeDailyTask.setSign(sign);
        //写回数据库
        String prizeDailyJson = new Gson().toJson(mPrizeDailyTask);
        mPrizeDbInit.setPrize_daily_json(prizeDailyJson);
        UserScoreDaoImpl.getInstance().updateUserPrize(mPrizeDbInit);
    }

    public ArrayList<PrizeDaily> exchangePrizeDaily(int betIndex, int prizeDailyIndex) {
        final int betIndexChecking = TurntableAddConfig.getBetIndex(betIndex);
        final int prizeDailyIndexChecking = TurntableAddConfig.getPrizeDailyIndex(prizeDailyIndex);
        PrizeDailyInfo prizeDailyInfo = mPrizeDailyTask.getPrizeDailyList().get(betIndexChecking);
        ArrayList<PrizeDaily> prizeDailyArrayList = prizeDailyInfo.exchangePrizeDaily(prizeDailyIndexChecking);
        for (PrizeDaily prizeDaily : prizeDailyArrayList) {
            mPrizeList.setPrizeLuckyValueAdd(prizeDaily.getPrizeLuckyValue());//加上幸运积分
            mPrizeList.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());//统计全部每日任务钻石
            mPrizeDailyTask.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());////统计每日任务钻石
        }
        return prizeDailyArrayList;
    }

    /**
     * 一键领取当前倍率任务的奖励
     */
    public ArrayList<PrizeDaily> exchangePrizeDailyAll(int betIndex) {
        final int betIndexChecking = TurntableAddConfig.getBetIndex(betIndex);
        PrizeDailyInfo prizeDailyInfo = mPrizeDailyTask.getPrizeDailyList().get(betIndexChecking);
        ArrayList<PrizeDaily> prizeDailyArrayList = prizeDailyInfo.exchangePrizeDailyAll();
        for (PrizeDaily prizeDaily : prizeDailyArrayList) {
            mPrizeList.setPrizeLuckyValueAdd(prizeDaily.getPrizeLuckyValue());//加上幸运积分
            mPrizeList.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());//统计全部每日任务钻石
            mPrizeDailyTask.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());//统计每日任务钻石

        }
        return prizeDailyArrayList;
    }

    /**
     * 一键领取所有任务的奖励
     */
    public ArrayList<PrizeDaily> exchangePrizeDailyAll() {
        ArrayList<PrizeDailyInfo> prizeDailyInfoArrayList = mPrizeDailyTask.getPrizeDailyList();
        ArrayList<PrizeDaily> prizeDailyArrayListAll = new ArrayList<>();
        for (PrizeDailyInfo prizeDailyInfo : prizeDailyInfoArrayList) {
            ArrayList<PrizeDaily> prizeDailyArrayList = prizeDailyInfo.exchangePrizeDailyAll();
            for (PrizeDaily prizeDaily : prizeDailyArrayList) {
                mPrizeList.setPrizeLuckyValueAdd(prizeDaily.getPrizeLuckyValue());//加上幸运积分
                mPrizeList.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());//统计全部每日任务钻石
                mPrizeDailyTask.setDailyTaskWinAdd(prizeDaily.getPrizeDiamondSend());//统计每日任务钻石
            }
            prizeDailyArrayListAll.addAll(prizeDailyArrayList);

        }
        return prizeDailyArrayListAll;
    }


    private void resetPrizeDaily() {
        String today = Utils.getFormattedDate();
        String db = mPrizeDailyTask.getDate();
        if (!today.equals(db)) {
            mPrizeDailyTask = new PrizeDailyTask();
            mPrizeDailyTask.initPrizeDaily(_betArray);
            String json = new Gson().toJson(mPrizeDailyTask);
            String code = String.format("UID=%s@JSON=%s@KEY=%s", _uid, json, RoomConfig.LUCKY_KEY);
            String sign = Utils.encryptMD5(code);//初始化玩家的幸运值签名
            mPrizeDailyTask.setSign(sign);//设置签名
            LogWindows.getLogWindows().printToTextArea("Reset:" + code, Prize.class);

            //初始化
            new Thread(this::write).start();//并且立即写入数据库
        }

    }


    private void resetPrizeDailyError(String initJson) {
        //读取数据库的时候需要判断是否数据被篡改
        final String signInit = mPrizeDailyTask.getSign();//保存原始签名;
        //拷贝一份新的 mPrizeDailyTask,加密比较,是否被篡改
        boolean isSuccess = checkingDailyTask(initJson, signInit);//如果有改动会在日志里显示,如果获取数据库数据被篡改,则重置数据
        if (!isSuccess) {
            mPrizeDailyTask = new PrizeDailyTask();
            mPrizeDailyTask.initPrizeDaily(_betArray);
            String json = new Gson().toJson(mPrizeDailyTask);
            String code = String.format("UID=%s@JSON=%s@KEY=%s", _uid, json, RoomConfig.LUCKY_KEY);
            String sign = Utils.encryptMD5(code);//初始化玩家的幸运值签名
            mPrizeDailyTask.setSign(sign);//设置签名
            LogWindows.getLogWindows().printToTextArea("ErrorReset:" + code, Prize.class);

            //初始化
            new Thread(this::write).start();//并且立即写入数据库
        }

    }


    /***
     * 幸运积分兑奖
     * @param prizeLuckyCode 幸运积分兑奖代号
     */
    public PrizeLucky exchangeLuckyValue(String prizeLuckyCode) {
        //1.通过代号获取兑奖的物品价值
        //2.核实玩家的积分是否满足兑换条件
        //3.发放奖品
        PrizeLuckyStore prizeLuckyShore = TurntableAddConfig.getConfig().getPrizeLuckyStore();
        long valueCurrent = Utils.checkingLuckyValue(mPrizeList.getUid(), mPrizeList.getPrizeLuckyValue(), mPrizeList.getSign());
        if (valueCurrent < 0) {//校验玩家的积分是否正常
            return null;
        }

        if (prizeLuckyCode.contains("AA-")) {
            return getPrizeVirtual(prizeLuckyCode, prizeLuckyShore);
        }
        if (prizeLuckyCode.contains("BB-")) {
            return getPrizeEntity(prizeLuckyCode, prizeLuckyShore);
        }
        return null;

    }//entity

    private PrizeLucky getPrizeVirtual(String prizeLuckyCode, PrizeLuckyStore prizeLuckyShore) {
        for (PrizeLucky prizeLucky : prizeLuckyShore.getPrizeLuckyList()) {

            if (prizeLuckyCode.equals(prizeLucky.getPrizeCode())) {//先校验是哪种奖品

                int prizeLuckyValue = prizeLucky.getLuckyValue();

                if (mPrizeList.getPrizeLuckyValue() - prizeLuckyValue >= 0) {//判断积分是否充足
                    mPrizeList.setPrizeLuckyValueLower(prizeLuckyValue);
                    mPrizeList.setExLuckyStoreAdd(prizeLucky.getPrizeDiamondSend());//统计玩家兑换虚拟钻石
                    mPrizeDailyTask.setExLuckyStoreAdd(prizeLucky.getPrizeDiamondSend());//统计今日兑换钻石
                    return prizeLucky;
                }

            }
        }
        return null;
    }

    private PrizeLucky getPrizeEntity(String prizeLuckyCode, PrizeLuckyStore prizeLuckyShore) {
        for (PrizeLucky prizeLucky : prizeLuckyShore.getPrizeLuckyList()) {

            if (prizeLuckyCode.equals(prizeLucky.getPrizeCode())) {//先校验是哪种奖品

                int prizeLuckyValue = prizeLucky.getLuckyValue();

                if (mPrizeList.getPrizeLuckyValue() - prizeLuckyValue >= 0) {//判断积分是否充足
                    mPrizeList.setPrizeLuckyValueLower(prizeLuckyValue);
                    String code = _uid + "_" + prizeLucky.getPrizeCode() + "_" + Utils.getTime() + "_" + System.currentTimeMillis();
                    prizeLucky.setPrizeRedemptionCode(code);
                    return prizeLucky;
                }

            }
        }
        return null;
    }


    public int getUid() {
        return _uid;
    }

    public PrizeList getPrizeList() {
        return mPrizeList;
    }

    public PrizeDailyTask getPrizeDailyTask() {
        return mPrizeDailyTask;
    }


}
